<template>
  <!-- <div :class=" isIOSHide ? 'hideTopBar': 'detail-wraper' "> -->
  <div class="detail-wraper">
    <EmailDetailSkeleton
      v-if="
        !Object.prototype.hasOwnProperty.call(mailDetail, 'content') &&
        isLoading
      "
    ></EmailDetailSkeleton>
    <Toast v-if="isLoading" :message="$lang.loading"></Toast>
    <div :class="newShowReply ? 'top-bar-zIndex' : 'top-bar'">
      <div class="inlineBlock" @click="back">
        <img src="@/assets/oppo/detail/back.svg" alt="" />
      </div>
      
      <!-- <p class="title-center" v-if="isNotification">{{ $lang.flashTips }}</p> -->
      <div v-if="isNotification">
        <div class="inlineBlock1" @click="delMessage" style="margin: 0px 8px">
          <img
            id="delete-icon"
            src="@/assets/oppo/detail/delete.svg"
            alt=""
          />
        </div>
        <div class="inlineBlock" style="margin:0 6px 0 8px">
          <img
            id="prev-icon"
            src="@/assets/oppo/detail/previousUnclick.svg"
            alt=""
          />
        </div>
        <div class="inlineBlock" style="margin-left: 7px">
          <img src="@/assets/oppo/detail/nextUnclick.svg" alt="" />
        </div>
      </div>
      <div v-if="!isNotification">
        <div class="inlineBlock1" @click="delMessage" style="margin: 0px 8px">
          <img
            id="delete-icon"
            src="@/assets/oppo/detail/delete.svg"
            alt=""
          />
        </div>
        <div v-if="hidePrevBtn" class="inlineBlock" style="margin:0 6px 0 8px">
          <img
            id="prev-icon"
            src="@/assets/oppo/detail/previousUnclick.svg"
            alt=""
          />
        </div>
        <div class="inlineBlock" v-else @click="goToPrevious" style="margin:0 6px 0 8px">
          <img
            id="prev-icon"
            src="@/assets/oppo/detail/previous.svg"
            alt=""
          />
        </div>
        
        <!--     v-if="!hideNextBtn" -->

        <div class="inlineBlock" v-if="hideNextBtn" style="margin-left: 7px">
          <img
            src="@/assets/oppo/detail/nextUnclick.svg"
            alt=""
          />
        </div>
        <div v-else @click="goToNext" class="inlineBlock" style="margin-left: 7px">
          <img
            style="color: black"
            src="@/assets/oppo/detail/next.svg"
            alt=""
          />
        </div>
        
      </div>
    </div>
    <section class="header-wraper">
      <div class="subject">
        <p class="subject-title">{{ mailDetail.subject }}</p>
        <div @click="controllFollow">
          <img
            :src="
              hasFollow
                ? require('@/assets/oppo/detail/hasFollow.svg')
                : require('@/assets/oppo/detail/notFollow.svg')
            "
            alt=""
          />
        </div>
      </div>
      <!-- 发送人信息 -->
      <div class="person-info">
        <div class="left">
          <div class="brief" v-show="isFold">
            <div class="text-address text-overflow">{{ mailAddresser }}</div>
            <div class="time-attach-wrapper">
              {{
                (mailDetail.receivedDateTime || mailDetail.createdDateTime)
                  | dateFormat("yyyy-MM-dd")
              }}

              <div
                class="attachs"
                v-if="attachmentList.length"
                @click="focusAttachs"
              >
                <div class="value text-overflow">
                  <img
                    :src="require('@/assets/oppo/attach.svg')"
                    alt=""
                    class="addEx"
                  />
                  {{ attachmentList && attachmentList.length }}
                </div>
              </div>
            </div>
          </div>
          <!-- <transition name="van-slide-down"> -->
          <!-- 详情展开信息 -->
          <div class="detail" v-show="!isFold">
            <div class="sender">
              <div class="title">{{ $lang.sender }}</div>
              <ul class="list-wraper">
                <li class="list">
                  <div class="name">
                    {{
                      mailDetail.sender
                        ? mailDetail.sender.name || $lang.sender
                        : $lang.sender
                    }}
                  </div>
                  <div class="mail-name text-overflow">
                    {{ mailDetail.sender ? mailDetail.sender.address : "-" }}
                  </div>
                </li>
              </ul>
            </div>
            <div
              class="reciver"
              v-if="mailDetail.toRecipients && mailDetail.toRecipients.length"
            >
              <div class="title">{{ $lang.receiver }}</div>
              <ul class="list-wraper">
                <li
                  class="list"
                  v-for="item in mailDetail.toRecipients"
                  :key="item.address"
                >
                  <div class="name">
                    {{ item.name || $lang.receiver }}
                  </div>
                  <div class="mail-name text-overflow">
                    {{ item.address }}
                  </div>
                </li>
              </ul>
            </div>
            <div
              class="reciver"
              v-if="
                mailDetail &&
                mailDetail.ccRecipients &&
                mailDetail.ccRecipients.length
              "
            >
              <div class="title">{{ $lang.copyer }}</div>
              <ul class="list-wraper">
                <li
                  class="list"
                  v-for="item in mailDetail.ccRecipients"
                  :key="item.address"
                >
                  <div class="name">
                    {{ item.name || $lang.copyer }}
                  </div>
                  <div class="mail-name text-overflow">
                    {{ item.address }}
                  </div>
                </li>
              </ul>
            </div>

            <div
              class="reciver"
              v-if="
                mailDetail &&
                mailDetail.bccRecipients &&
                mailDetail.bccRecipients.length
              "
            >
              <div class="title">{{ $lang.privatelyPerson }}</div>
              <ul class="list-wraper">
                <li
                  class="list"
                  v-for="item in mailDetail.bccRecipients"
                  :key="item.address"
                >
                  <div class="name">
                    {{ item.name || $lang.privatelyPerson }}
                  </div>
                  <div class="mail-name text-overflow">
                    {{ item.address }}
                  </div>
                </li>
              </ul>
            </div>

            <div class="time">
              <div class="title">{{ $lang.time }}</div>
              <div class="value text-overflow">
                {{
                  (mailDetail.receivedDateTime || mailDetail.createdDateTime)
                    | dateFormat()
                }}
              </div>
            </div>
            <div
              class="attachs"
              v-if="attachmentList.length"
              @click="focusAttachs"
            >
              <div class="title">{{ $lang.attachment }}</div>
              <div class="value text-overflow">
                <img :src="require('@/assets/oppo/attach.svg')" alt="" />
                {{ attachmentList.length }}
              </div>
            </div>
          </div>
        </div>
        <div
          class="right"
          @click="isFold = !isFold"
          v-show="Object.keys(mailDetail).length > 0 && isLoading == false"
        >
          {{ isFold ? $lang.detail : $lang.hide }}
        </div>
      </div>
    </section>
    <div class="van-hairline--top" v-show="mailDetail.meetingMessage"></div>
    <!-- 会议邀约信息 -->
    <div class="meeting-info" v-if="mailDetail.meetingMessage">
      <div class="meeting-time">
        <img
          :src="require('@/assets/oppo/detail/time.svg')"
          alt=""
          class="meeting-icon"
        />
        <span class="meeting-text"
          >{{ $lang.meetingTime }}{{ $lang.symbelColon }}{{ meetingTime }}</span
        >
      </div>
      <div class="meeting-site">
        <img
          :src="require('@/assets/oppo/detail/site.svg')"
          alt=""
          class="meeting-icon"
        />
        <span class="meeting-text"
          >{{ $lang.meetingPlace }}：{{
            mailDetail.location && mailDetail.location.displayName
          }}</span
        >
      </div>
    </div>
    <div class="van-hairline--top"></div>
    <div class="content-wraper" id="content-wraper">
      <!-- <div class="flex-wraper"> -->
      <section
        v-if="!mailDetail.encrypt"
        class="content email-detail-content"
        id="content"
        ref="content"
        :style="dynamicStyle"
        v-html="mailContent"
        @click="clickHandle"
      ></section>
      <encrypted-email v-if="mailDetail.encrypt" class="content email-detail-content" :webLink="mailDetail.webLink"></encrypted-email>
      <div id="attachs-comtainer" v-show="attachmentList.length" :style="{top: attachTop + 'px'}">
        <div class="attachs" id="focusAttach" >
          <img :src="require('@/assets/oppo/attach.svg')" alt="" />
          <span style="fontSize:18px">{{ $lang.attachment }}</span>
        </div>
        <attach-list
          v-show="attachmentList.length"
          ref="attach"
          id="attachOfList"
          :messageID="id"
          :isEmailDetail="true"
          :key="id"
          v-model="attachmentList"
        ></attach-list>
      </div>
      <!-- <div class="end-text">{{ $lang.mailEnd }}</div> -->
    </div>
    <!-- 快速回复 -->
    <quick-reply
      v-if="hasReply && isShowQuickReply && Object.keys(mailDetail).length > 0"
      :mailDetail="mailDetail"
      ref="quickReplyDom"
    >
      <div class="reply-input-wraper">
        <textarea
          placeholder="$lang.quickReply"
          class="reply-input"
          v-model="replyForm.s"
        />
      </div>
      <div class="reply-bt">
        <van-button
          size="small"
          style="width: 48px; margin-left: 8px"
          type="info"
          @click="quickReply"
          >{{ $lang.reply }}</van-button
        >
      </div>
    </quick-reply>
  </div>
</template>

<script>
import QuickReply from "@/components/QuickReply.vue";
import Toast1 from "@/plugins/Toast/Toast";
import {
  getUrlParam,
  dateFormat,
  dateWeek,
  isWithHtml,
  isMobile,
  changeTabRead,
  addWatermarkImg,
} from "@/utils/helper.js";

import { mapGetters } from "vuex";
import EmailDetailSkeleton from "@/components/EmailDetailSkeleton.vue";
import { AttachList } from "@/components";
import Toast from '../plugins/Toast/Toast.vue';
import EncryptedEmail from "@/components/EncryptedEmail.vue";
export default {
  name: "EmailDetail",
  components: {
    QuickReply,
    EmailDetailSkeleton,
    AttachList,
    Toast,
    Toast1,
    EncryptedEmail
  },
  watch: {
    $route(newV) {
      console.warn("route change!!");
      console.warn(newV);

      this.dataInit();
       this.$nextTick(()=>{        
         try{          
           window.scrollTo({top: 0, behavior: "instant"});        
         }catch(e){          
           window.scrollTo(0, 0);        
          }       
        })
    },
    "$route.query.index": {
      handler(newV) {
        if (newV == 0) {
          this.hidePrevBtn = true;
        }
        this.attachTop = null;
        this.heightAfter = 0;
        this.bottomOffset = 0;//生产环境365异常邮件
        const i = this.currentFolderList.length - 1;
        console.warn("length  ", i);
        if (newV == this.currentFolderList.length - 1) {
          console.warn("watch------");
          console.warn("currentListNextUrl------", this.currentListNextUrl);
          if (!this.currentListNextUrl) {
            this.hideNextBtn = true;
            // this.$notify({ type: "primary", message: "已为最后一封" });
          } else {
            this.appendCurrentFolderList(this.currentListNextUrl);
          }
        }
      },
      immediate: true,
    },
  },
  computed: {
    ...mapGetters([
      "mailType",
      "folderInfo",
      "currentFolderList",
      "currentListNextUrl",
      "newShowReply",
    ]),
    indexInFolder() {
      return this.$route.query.index;
    },
    id() {
      return this.$route.params.id;
    },
    hasReply() {
      return this.mailType !== "draft";
    },
    mailContent() {
      return this.contentHtmlFilter(this.mailDetail.content);//对内容进行修改
    },
    mailAddresser() {
      if (this.mailDetail.sender) {
        let addr =
          this.mailDetail.sender?.name || this.mailDetail.sender?.address;
        return addr;
      }
      return "";
    },
    isShowQuickReply() {
      if (this.$route?.query?.type) {
        if (this.$route.query.type === "sent") {
          return false;
        }
      }
      return true;
    },
    // 动态控制富文本显示
    dynamicStyle() {
      // 初始化数据
      // this.maxTableWidth = 0;
      this.bottomOffset = 0;
      this.isFold = true;
      this.attachTop = null;
      this.heightAfter = 0;
      if (
        this.mailContent &&
        isWithHtml(this.mailContent) &&
        (this.maxTableWidth > document.body.clientWidth - 40)
      ) {
        //屏幕宽度 clientW
        const clientW = document.body.clientWidth - 40;
        // console.warn("clientW" + " " + clientW); //(屏幕宽度-padding)=(375 -40)335

        const ele = document.getElementById("content");
        let params = ele.getBoundingClientRect();

        const hiBefore = params.height;
        console.warn("压缩前的最低高度hiBefore:  " + hiBefore);
        let ratio = clientW / this.maxTableWidth;
        console.warn("压缩倍率 ratio：" + ratio);
        this.$nextTick(() => {
          params = ele.getBoundingClientRect();
          const hiAfter = params.height;
          this.heightAfter = hiAfter;
          console.warn("压缩后的最低高度 hiAfter：" + hiAfter);

          this.attachTop = hiAfter + 60;  //附件定位
          console.warn("附件定位 attachTop" + this.attachTop);
          const isIOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //判断是否是 iOS终端 
          const iSOfficeEmail = this.iSOfficeEmail();
          if(iSOfficeEmail) {
            this.bottomOffset = -(hiBefore - hiAfter)/ratio - 240;
          } else if(isIOS){
            this.bottomOffset =  -(hiBefore - hiAfter)/ratio - 240;
          } else {
            this.bottomOffset =  -(hiBefore - hiAfter)*ratio ;
          }

          //bottomOffset= before高度 - 缩短后的高度
          console.warn("压缩差值 bottomOffset: " + this.bottomOffset);
        });
        return {
          width: `${this.maxTableWidth}px`,
          transform: `scale3d(${ratio}, ${ratio},1)`,
        };
      } else {
        //针对一个div标签中全包含字母或英文，应使它break-word
        return {
          wordWrap: "break-word",
          // wordBreak: "break-all",
        };
      }
    },
    // 计算会议时间
    meetingTime() {
      //  let startDate = dateFormat(this.mailDetail.startDateTime,'yyyy-MM-dd')
      let startTime = dateFormat(this.mailDetail.startDateTime, "h:mm");
      let week = dateWeek(this.mailDetail.startDateTime);
      let endTime = dateFormat(this.mailDetail.endDateTime, "h:mm");
      console.warn(week, "~~~~~~~~~");
      return `${week} ${startTime}-${endTime}`;
    },
  },
  data() {
    return {
      mailDetail: {},
      attachmentList: [],
      replyForm: {
        mailName: "",
        uid: "",
        s: "",
      },
      isFold: true,
      isLoading: true,
      maxTableWidth: "",
      bottomOffset: 0,
      hasFollow: false,
      hidePrevBtn: false,
      hideNextBtn: false,
      isNotification: false,
      isIOSHide: false,
      nowScale: 1, //当前缩放比例
      parentFolderId:"",
      attachTop: null,
      heightAfter:0
    };
  },

  created() {
    console.warn(this.folderInfo);
    this.$imbedapi(666001005, "goToEmailDetail").then((res) => {
      console.warn(res, "进入详情页面埋点");
    });
    window.qing.call("setBounce", { enable: 0 });
    const officeemail = decodeURI(
      getUrlParam("officeemail", window.location.href)
    );
    if (officeemail) {
      this.isNotification = true;
    }
    this.dataInit();
    // const that = this;
    // window.qing.on("appear", function (e) {
    document.addEventListener("visibilitychange", () => {
      if (document.visibilityState === "visible") {
        console.warn("页面进入前台");
        // that.dataInit()
      }
    });
    //监听当前的缩放比例
    window.visualViewport.addEventListener("resize", function () {
      this.nowScale = this.scale;
      // console.warn("手势缩放比例：", this.scale);
    });
    const _this = this;
    window.qing.call("defback", {
      // 阻止 安卓 左划/home键 返回
      success: function () {
        _this.back();
      },
    });
    console.warn("navigator.userAgent",navigator.userAgent);
    const isIOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //判断是否是 iOS终端 
    if (isIOS) {
      //禁用IOS的左滑
      let startX, startY;
      document.addEventListener("touchstart", function (e) {
        startX = e.targetTouches[0].pageX;
        startY = e.targetTouches[0].pageY;
      });
      document.addEventListener(
        "touchmove",
        function (e) {
          if (e.touches.length > 1) {
            console.warn("多触点", e.touches);
            return;
          }
          if (this.nowScale === 1) {
            //缩放状态 不禁止左滑
            let moveX = e.targetTouches[0].pageX;
            let moveY = e.targetTouches[0].pageY;
            if (Math.abs(moveX - startX) > Math.abs(moveY - startY)) {
              console.warn("禁用IOS的左滑");
              e.preventDefault();
            }
          }
        },
        { passive: false }
      );
    }
  },
  mounted() {
    window.qing.call("setWebBottomInset", {
      show: true, //底部增加34偏移量
      success: function (res) { 
        console.warn(res,"调用适配iponeX的桥增加34偏移量");
      },
    });

    window.openInBridge = this.openInBridge
    
  },
  updated() {
    addWatermarkImg("content-wraper");
    this.$nextTick(() => {
      if(this.bottomOffset){
        this.$refs.content.style.marginBottom = `${parseInt(
          this.bottomOffset
        )}px`;
        if(this.heightAfter){  // 将子级脱离文档的高度 同步给 父级高度
          const d = document.getElementById("content-wraper");
          d.style.height = this.heightAfter + 60 +'px';
        }
      }else{
        this.$refs.content.style.marginBottom = "0";
      }
      
    });
    // console.warn("zzzzzzzzzz",this.dynamicStyle,isWithHtml(this.mailContent),this.maxTableWidth , document.body.clientWidth - 40)
    // console.warn("updated maxtabwidth :::::",this.maxTableWidth);
  },
  methods: {
    //office365报错邮件 表格部分能缩放  但是下方文字不能换行  特殊处理
    iSOfficeEmail() {
      const data = this.mailDetail;
      if(data && data.webLink && data.webLink.indexOf("office365") > -1){
          return true;
      }
      return false;
    },

    /**到达最后一封邮件后 再获取新的列表追加到list */
    async appendCurrentFolderList(nextUrl) {
      try {
        const requestBody = {
          nextUrl,
          folderId: this.folderInfo.folderId,
        };
        const res = await this.Api.listMeByFolderId(requestBody);
        const { success, data } = res?.data;
        const list = data?.list;
        if (success) {
          if (this.currentFolderList.length) {
            let tmp = this.currentFolderList.concat(list);
            console.warn("新的邮件列表数据", tmp);
            this.SAVECURRENTFOLDERLIST(tmp);
            this.SAVECURRENTLISTNEXTURL(data?.nextUrl);
          }
        }
      } catch {
        console.error("获取追加邮件列表失败");
      }
    },
    goToPrevious() {
      this.hideNextBtn = false;
      // if (this.indexInFolder == 0) {
      //   // this.$notify({ type: "primary", message: "已为第一封" });
      //   this.hidePrevBtn = true;
      //   return;
      // }
      const preIdx = parseInt(this.indexInFolder) - 1;
      const folderId = this.currentFolderList[preIdx]?.id;
      //清空回复草稿
      this.$refs.quickReplyDom.replyMessageClear();
      this.$router.replace({
        path: `/emaildetail/${folderId}`,
        query: {
          index: preIdx,
        },
      });
      this.$toast.loading({
        message: this.$lang.loading,
        forbidClick: true,
        duration: 0,
      });
    },
    goToNext() {
      console.warn("gotoNext-----",this.currentFolderList);
      this.hidePrevBtn = false;
      const nextIdx = parseInt(this.indexInFolder) + 1;
      //如果到了最后一个mail
      if (nextIdx === this.currentFolderList.length) {
        //watch中调用 appendCurrentFolderList
      } else if (nextIdx < this.currentFolderList.length) {
        const idInFolder = this.currentFolderList[nextIdx].id;
        //清空回复草稿
        this.$refs.quickReplyDom.replyMessageClear();
        this.$router.replace({
          path: `/emaildetail/${idInFolder}`,
          query: {
            index: nextIdx,
          },
        });
        this.$toast.loading({
          message: this.$lang.loading,
          forbidClick: true,
          duration: 0,
        });
      }
    },
    back() {
      // this.folderInfo.folderId
      if (isMobile() && window.qing.isSupportNativeJsBridge) {
        window.qing.call("closeWebView");
      } else {
        this.$router.push("/home");
      }
    },
    async delMessage() {
      const arr = [];
      let res;
      arr.push(this.id);
      try {
        const result = await this.Api.getFolderInfo(this.parentFolderId);
        if(result && result.data && result.data.data){
            console.warn(result.data.data.displayName);
            const curType = result.data.data.displayName;
            //已删除文件夹内的话直接删除，否则先移动到已删除文件夹
            if (curType === "deleteditems" || curType === "deleted" || curType === "已删除文件夹" || curType === "Deleted Items" || curType === "已删除" || curType === "已删除邮件") {
              res = await this.Api.batchDelete({
                ids: arr,
              });
            } else {
              res = await this.Api.batchMoveDel({
                folderId: "deleteditems",
                ids: arr,
              });
            }

            if(res){
            const { success } = res?.data;
            if (success) {
              this.$imbedapi(666001003, "delMail").then((res) =>
                console.warn(res, "邮件删除")
              );
              }else{
                // console.warn("飞了出去");
                return 
              }
              //确认弹窗 然后返回列表页
              this.$toast.success(this.$lang.successDelete);
              if (isMobile() && window.qing.isSupportNativeJsBridge) {
                setTimeout(() => {
                  window.qing.call("closeWebView");
                }, 900);
              } else {
                this.$toast.success(this.$lang.successDelete);
                this.$router.replace("/home");
              }
            }
        }
      } catch(e){
        // this.$toast.fail("删除失败");
        this.$toast.fail(this.$lang.DelFail)
        console.error("删除失败,查看当前报错",e);
      }
    },
    async controllFollow() {
      this.$toast.loading({
        message: this.$lang.loading,
        forbidClick: true,
        duration: 0,
      });
      try {
        const res = await this.Api.controllFollow(this.id);
        const { success,data } = res?.data;
        if (success && data) {
          this.$toast.clear();
          this.$toast.success(this.$lang.successMark)
          this.hasFollow = !this.hasFollow;
        }else{
          this.$toast.clear();
          this.$toast.success(this.$lang.followFailed)
          this.hasFollow = !this.hasFollow;
        }
      } catch {
        console.error("关注失败");
      }
    },
    clickHandle(e) {
      const href =
        e?.target?.href ||
        e?.target?.parentElement?.href ||
        e?.target?.children[0]?.href ||
        "";
      e.preventDefault();
      window.qing.call("localFunction", {
        name: "openExtBrowser",
        param: {
          url: href,
        },
        success: function () {
          console.success("跳转外部成功");
        },
      });
      // console.error(e.target.nodeName === 'A')
    },
    // 快速回复
    async quickReply() {
      if (!this.replyForm.s) {
        this.$toast.fail(this.$lang.replyCanNot);
        return;
      }
      this.replyForm.mailName = this?.mainEmail?.emailName;
      this.replyForm.uid = this?.mailDetail?.uid;
      const params = {
        ...this.replyForm,
      };
      try {
        const res = await this.Api.replyMail(params);
        const { success } = res?.data;
        if (success) {
          window.qing.call("toast", {
            msg: "回复成功",
          });
          setTimeout(() => {
            window.qing.call("closeWebView");
          }, 300);
          // this.$router.push('/home')
        } else {
          console.error("回复失败");
        }
      } catch {
        console.error("回复失败");
      }
    },

    getAttachmentByte(messageId, attachmentId) {
      return `/mail-office365-exchange/attachment/getAttachmentByte?messageId=${messageId}&attachmentId=${attachmentId}`;
    },

    async dataInit() {
      const id = this.$route.params.id;
      //点击下一封 初始化数据
      this.maxTableWidth = 0;
      this.bottomOffset = 0;
      this.isFold = true;
      this.attachTop = null;
      this.heightAfter = 0;

      console.warn("dataInit id!!", id);
      let errors = "";
      try {
        const res = await this.Api.getMailDetail(id);

        const { success, data, errorCode } = res?.data;
        errors = errorCode;
        if (success) {
          this.mailDetail = res?.data?.data;
          this.hasFollow = this.mailDetail?.follow;
          this.parentFolderId = this.mailDetail?.parentFolderId;
          console.warn("这是邮件详情获取的信息", this.mailDetail);
          //获取mailDetail.content中富文本table标签的最大宽度
          this.$nextTick(() => {
            const tables = document.getElementsByTagName("table");
            if (tables.length) {
              let max = 300;
              for (let i = 0; i < tables.length; i++) {
                if (tables[i].width > max) {
                  max = tables[i].width;
                }
              }
              this.maxTableWidth = max;
              // console.warn("maxwidth:::::"+this.maxTableWidth);
            }else{
              this.maxTableWidth = 0;
              // console.warn("max rest wei 0:::::"+this.maxTableWidth);
            }

            // const content = document.querySelector('#content')
            // const images = Array.from(content.querySelectorAll('img'))
            // console.warn('images', images)
            // images.map(item => {
            //   item.style.maxWidth = '100%'
            //   item.style.height = 'auto'
            // })
          });

          if (data?.attachments?.length) {
            let attachsListTmp = [];
            attachsListTmp= data?.attachments.map((f) => {
              const r = {};
              r["contentType"] = f.contentType;
              r["id"] = f.id;
              r["content"] = this.getAttachmentByte(this.id, f.id);
              r["file"] = "File";
              r["fileName"] = f.name;
              r["fileSize"] = f.size;
              r["fileUrl"] = "";
              r["status"] = "finished";
              // r['fileType']  ='image/png'
              // r['fileUrl']=this.getAttachmentByte(this.messageId, f.id)
              // r['fileExtIcon'] = fileIcon(getFileExt(f.fileName))
              return r;
            });
            this.attachmentList = attachsListTmp;  //重新赋值  触发列表视图更新
          } else {
            this.attachmentList = [];
          }
          this.isLoading = false;
          setTimeout(() => {
            this.$toast.clear();
          }, 800);
          setTimeout(() => {
            changeTabRead();
          },3000 )
        } else {
          console.error("获取详情失败");
          if (errors == 50010) {
            this.isLoading = false;
            this.$toast.fail(this.$lang.messageDelMov);
          } else {
            this.$toast.fail(this.$lang.getDetailFailed);
          }
        }
      } catch (e) {
          this.isLoading = false;
        errors = e?.data?.errorCode;
        if (errors == 50010) {
          this.$toast.fail(this.$lang.messageDelMov);
          if (isMobile() && window.qing.isSupportNativeJsBridge) {
            setTimeout(() => {
            window.qing.call("closeWebView");
            }, 2000);
          } else {
            setTimeout(() => {
              this.$router.replace("/home");
            }, 2000)
          }
        } else {
          this.$toast.fail(this.$lang.getDetailFailed);
          if (isMobile() && window.qing.isSupportNativeJsBridge) {
            setTimeout(() => {
            window.qing.call("closeWebView");
            }, 2000);
          } else {
            setTimeout(() => {
              this.$router.replace("/home");
            }, 2000)
          }
        }
      }
    },
    //聚焦附件列表
    focusAttachs() {
      const dom = document.getElementById("attachs-comtainer");
      if(dom){
        window.scrollTo({
          top: dom.offsetTop - 100,
          behavior: "smooth",
        });
      }
    },

    //点击跳转事件
    contentHtmlFilter(content) {
      if(content){
        //部分邮件数据存在回车符换行，无法识别，替换成换行标签
        content = content.replace(/[\r\n]/g,"<br/>");
        let code = content.split("<a ");
        if(code.length > 0){
          for(let i= 1; i< code.length; i++){
            let str = code[i]; 
            //匹配出href里面的链接
            if(str.match(/href="(\S*)"/) && str.match(/href="(\S*)"/).length > 0 && str.match(/href="(\S*)"/)[1].indexOf("notifyType=email") > -1 ){
              // console.warn("strstrstrstrstrstr",str)
              const tmp = str.match(/href="(\S*)"/); 
              str = str.replace(tmp[0], "")
              if(str.indexOf('target="_blank"') > -1){
                str = str.replace('target="_blank"', '');
              }
              str = `onClick="openInBridge(\'${tmp[1]}\')" ` + str;
              code[i] = str;
            }
          }
          content =  code.join("<a style='color:#0000EE'");
        }
      }
      return content;
    },
    openInBridge(url){
      if (isMobile() && window.qing.isSupportNativeJsBridge) {
        const sender = this.mailDetail.sender?.name || "undefind" 
        url = url + "&notify_device=TT";
        console.warn("JS桥内部,跳转的链接是 =》url,sender: ", url , sender)
        window.qing.call("gotoLightApp", {
          urlParam: url,
          appId:"100000",
          appName: sender,
        });
      } else {
        url = url + "&notify_device=PC";
        console.warn("JS桥外部－PC，跳转的链接是 =》 ", url)
        window.open(url);
      }
    }
  },
};
</script>

<style lang="less" scoped>
.inlineBlock{
  display: inline-block;
  img{
    pointer-events: none;
  }
}
.inlineBlock1{
  display: inline-block;
  // margin-right: 16px;
}
.detail-wraper {
  height: 100%;
  // overflow-y: auto; //解决iphone7纯图片滚动问题
  width: 100%;
  position: relative;
  padding-top: 44px;
  background: #fff !important;
  .attachs{
    img{
      pointer-events: none;
    }
  }
  .top-bar {
    position: fixed;
    top: 0;
    display: flex;
    align-items: center;
    width: 100%;
    z-index: 999;
    height: 44px;
    padding: 0 16px;
    background: #fff;
    justify-content: space-between;
    box-sizing: border-box;
    #delete-icon {
      // margin-right: 16px;
    }
    #prev-icon {
      // margin-right: 13px;
    }
    .title-center {
      font-size: 18px;
      font-weight: 600;
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
    }
  }

  .top-bar-zIndex {
    position: fixed;
    top: 0;
    display: flex;
    align-items: center;
    width: 100%;
    z-index: 0;
    height: 44px;
    padding: 0 16px;
    background: #fff;
    justify-content: space-between;

    #delete-icon {
      margin-right: 16px;
    }
    #prev-icon {
      margin-right: 13px;
    }
    .title-center {
      font-size: 18px;
      font-weight: 600;
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
    }
  }

  .header-wraper {
    display: flex;
    padding: 16px;
    font-size: 14px;

    flex-direction: column;
    // border-bottom: 1px solid #ccc;
    position: relative;
    background: #fff !important;
    // z-index: 999;
    & > div {
      padding: 4px 0;
      display: flex;
      align-items: center;
    }
    .person-info {
      display: flex;
      flex-wrap: nowrap;
      width: 100%;
      min-height: 20px;
      overflow-y: auto;
      align-items: flex-start;
      transform: translateZ(0);
      transition-duration: 0.1;
      .left {
        // width: calc(100% - 40px);
        width: calc(100% - 1.200001704543rem);

        position: relative;
        z-index: -1;
        .brief {
          color: #323233;
          font-size: 14px;
          // .text-address {
          // line-height: 14px;
          // }
          .time-attach-wrapper {
            margin-top: 8px;
            display: flex;
            // flex-direction: column;
            color: #969799;
            justify-content: flex-start;
            align-items: center;
          }
        }
        .detail {
          font-size: 13px;
          line-height: 20px;
          color: #969799;
          & > div {
            width: 100%;
            display: flex;
            padding: 0.1066668181816rem 0;
          }
          .attachs {
            .value {
              display: flex;
              align-items: center;
              img {
                position: relative;
                top: 1px;
              }
            }
          }
          .list-wraper {
            width: 80%;
            .list {
              width: 100%;
              margin-bottom: 0.0800001136362rem;
              .name {
                color: #1d1d1d;
              }
              .mail-name {
                width: 100%;
              }
            }
          }
          .title {
            min-width: 1.1200015909068rem;
            text-align: right;
            padding-right: 0.266667045454rem;
            box-sizing: content-box;
          }
        }
      }
      .right {
        width: 1.200001704543rem;
        box-sizing: border-box;
        color: #00c00e;
        text-align: right;
        &:active {
          background: #ccc;
        }
      }
    }
    .email-color {
      color: #0085cc;
      padding-left: 10px;
    }
    .subject {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      font-size: 20px;
      line-height: 24px;
      color: #222;
      font-weight: 700;
      word-break: break-word;
      position: relative;
      // z-index: 999;
      padding-bottom: 16px;

      img{
        pointer-events: none;
      }
    }
    .subject-title {
      font-size: 16px;
      line-height: 0.6400009090896rem;
      font-weight: 600;
      margin-right: 16px;
      word-break: break-all;
    }
  }
  .meeting-info {
    width: 100%;
    min-height: 56px;
    padding: 12px 16px;
    .meeting-time {
      margin-bottom: 8px;
    }
    .meeting-text {
      font-size: 12px;
      color: #646566;
      line-height: 12px;
      font-weight: 400;
    }
    .meeting-icon {
      width: 16px;
      height: 16px;
      margin-right: 6px;
      vertical-align: middle;
    }
  }
  .content-wraper {
    padding: 25px 16px 60px;
    margin-bottom: 50px;
    min-height: 75vh;
    background: #fff;
    position:relative;
    border-top:1px solid #ebedf0;
    #attachs-comtainer{
      position: absolute;
      left: 0;
      right: 0;
      padding: 0 16px;
      background: #fff;
      padding-bottom: 60px;
    }
    .content {
      width: 100%;
      font-size: 14px;
      overflow-x: auto;
      min-height: 14px;
      line-height: 1.5;
      transform-origin: 0 0;
    }
    .attachs {
      padding-top: 20px;
      color: #969799;
      display: flex;
      align-items: center;
      span {
        margin-left: 5px;
      }
    }
    .attachment-wraper {
      width: 100%;
      padding: 0 20px;
      cursor: pointer;
      ul {
        width: 100%;
        height: 100%;
        li {
          height: 64px;
          // background-color: #f2f4f5;
          background-color: #e6e6e6;

          font-size: 16px;
          margin-top: 10px;
        }
      }
      .attachment-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 10px;

        .file-info {
          height: 100%;
          width: 100%;
          display: flex;
          align-items: center;
          .left {
            img {
              height: 40px;
              height: 40px;
              font-size: 16px;
            }
          }
          .right {
            padding-left: 20px;
            & > div {
              height: 50%;
              font-family: PingFangSC-Medium;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
            .title {
              font-size: 13px;
              color: #212121;
              font-weight: 700;
              // line-height: 24px;
              padding: 4px 0;
            }
            .size {
              font-size: 13px;
              font-size: 12px;
              color: #777;
            }
          }
        }
      }
    }
    .end-text {
      margin: 20px 0 11px 0;
      text-align: center;
      font-size: 14px;
      color: #969799;
      line-height: 14px;
      font-weight: 400;
    }
  }
  .reply-input-wraper {
    padding: 4px;
    flex: 1;
    height: 100%;
    overflow: auto;
    .reply-input {
      width: 100%;
      height: 100%;
      background: #f6f6f6;
      border: 1px solid hsla(240, 1%, 82%, 0.5);
      border-radius: 3px;
      padding-left: 8px;
      resize: none;
      overflow: auto;
      font-size: 16px;
      line-height: 2;
    }
  }
  .reply-bt {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .bottom-wrapper {
    font-size: 14px;
    position: fixed;
    bottom: 0;
    width: 100%;
    height: 42px;
    display: flex;
    justify-content: space-around;
    align-items: center;
    background: white;
    border-top: 1px outset #eeeff5;
    .btn-wrapper {
      width: 50%;
      height: 25px;
      display: flex;
      justify-content: center;
      position: relative;
      &:first-child {
        border-radius: 10px;
        border-right: 1px inset #eeeeee;
      }

      .bottom-btn {
        position: absolute;
        top: -8px;
        width: 100%;
        height: 40px;
        // background-color: #eeeeee;
        // border-radius: 30px;
        display: flex;
        justify-content: center;
        align-items: center;
        .bottom-icon {
          margin-right: 10px;
          height: 26px;
        }
        .bottom-icon2 {
          margin-right: 10px;
          height: 18px;
        }
      }
    }
  }
}
// 补充样式
.addEx {
  position: relative;
  top: 3px;
  left: 4px;
}
</style>
<style>
.detail-wraper .email-detail-content img {
  max-width: 100%;
  height: auto !important;
}

b, strong{
  font-weight: bold;
}
i, em {
  font-style: italic;
}
h1{
  font-size: 1.5em;
  margin-block-start: 0.83em;
  margin-block-end: 0.83em;
}
h2{
  display: block;
  font-size: 1.5em;
  margin-block-start: 0.83em;
  margin-block-end: 0.83em;
  margin-inline-start: 0px;
  margin-inline-end: 0px;
  font-weight: bold;
}
h3{
  display: block;
  font-size: 1.17em;
  margin-block-start: 1em;
  margin-block-end: 1em;
  margin-inline-start: 0px;
  margin-inline-end: 0px;
  font-weight: bold;
}
h4{
  display: block;
  margin-block-start: 1.33em;
  margin-block-end: 1.33em;
  margin-inline-start: 0px;
  margin-inline-end: 0px;
  font-weight: bold;
}
h5{
  display: block;
  font-size: 0.83em;
  margin-block-start: 1.67em;
  margin-block-end: 1.67em;
  margin-inline-start: 0px;
  margin-inline-end: 0px;
  font-weight: bold;
}
h6{
  display: block;
  font-size: 0.67em;
  margin-block-start: 2.33em;
  margin-block-end: 2.33em;
  margin-inline-start: 0px;
  margin-inline-end: 0px;
  font-weight: bold;
}
section img{
  pointer-events: none; 
}
</style>
